package com.clouddot.baipai.http;


import com.clouddot.baipai.infrastructure.environment.Env;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by wxy on 2018/4/8.
 */

public class ScanFaceHelper {
    public static ScanFaceHelper instance;

    public static ScanFaceHelper getInstance(){
        if(instance == null){
            instance = new ScanFaceHelper();
        }
        return instance;
    }
    private OkHttpClient okHttpClient;

    public ScanFaceHelper(){
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(5, TimeUnit.SECONDS);
        builder.readTimeout(5, TimeUnit.SECONDS);
        builder.writeTimeout(5, TimeUnit.SECONDS);
        okHttpClient = builder.build();
    }

    public String getComplex(String url) {
        String str = "";
        Request request = null;
        Response response = null;
        try {
            request = new Request.Builder().url(url).build();
            response = okHttpClient.newCall(request).execute();
            if(response.isSuccessful()){
                str = response.body().string();
            }
        } catch (IOException e) {
            Env.error(e);
            return "error";
        }

        return str;
    }

    /**
     * post表单请求提交,获取json字符串
     *
     * @param url
     * @param params
     */
    public Call postComplexForm(String url, Map<String, String> params) {

        FormBody.Builder builder = new FormBody.Builder();
        if (null != params && !params.isEmpty()) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                builder.add(entry.getKey(), entry.getValue());
            }
            RequestBody requestBody = builder.build();//创建请求体
            Request request =  new Request.Builder().url(url)
                    .post(requestBody).build();
            Call call = okHttpClient.newCall(request);
            return call;
        }
        return null;
    }

}
